<template>
  <div class="container">
    <div class="header">
      <el-select v-model="form.semester" placeholder="请选择学期" @change="filterPunishments" style="width: 200px; margin-right: 10px;">
        <el-option label="全部学期" :value="null" />
        <el-option v-for="item in semesterOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="form.classId" placeholder="请选择班级" @change="filterPunishments" style="width: 200px; margin-right: 10px;">
        <el-option label="全部班级" :value="null" />
        <el-option v-for="item in classOptions" :key="item.classId" :label="item.className" :value="item.classId" />
      </el-select>
      <el-button type="primary" @click="handleAdd">添加惩罚记录</el-button>
    </div>

    <el-table
      :data="paginatedPunishmentList"
      border
      stripe
      highlight-current-row
      style="width: 100%; margin-bottom: 20px; font-size: 11px;"
      v-loading="loading"
      max-height="calc(100vh - 200px)"
      empty-text="暂无数据"
    >
      <el-table-column prop="recordId" label="记录号" width="70" sortable />
      <el-table-column label="学生" width="90" sortable>
        <template #default="scope">
          <el-tag size="small">{{ getStudentName(scope.row.studentId) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="教师" width="90" sortable>
        <template #default="scope">
          <el-tag size="small">{{ getTeacherName(scope.row.teacherId) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="penaltyItemId" label="处罚项目ID" width="90" sortable />
      <el-table-column prop="recordTime" label="记录时间" width="100" sortable />
      <el-table-column prop="reviewStatus" label="审核状态" width="90" sortable>
        <template #default="scope">
          <el-tag :type="scope.row.reviewStatus === '已审核' ? 'success' : 'warning'" size="small">
            {{ scope.row.reviewStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" />
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="scope">
          <el-button-group>
            <el-button size="small" @click="handleEdit(scope.row)" icon="Edit" type="primary">编辑</el-button>
            <el-button size="small" @click="handleDelete(scope.row.recordId)" icon="Delete" type="danger">删除</el-button>
            <el-button 
              size="small" 
              @click="handleReview(scope.row)" 
              icon="Check" 
              type="success" 
              :disabled="scope.row.reviewStatus === '已审核'"
            >
              {{ scope.row.reviewStatus === '已审核' ? '已审核' : '审核' }}
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="total, sizes, prev, pager, next"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      style="margin-top: 20px; text-align: right"
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="学期" prop="semester">
          <el-select v-model="form.semester" placeholder="请选择学期" style="width: 100%">
            <el-option v-for="item in semesterOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="form.classId" placeholder="请选择班级" style="width: 100%">
            <el-option v-for="item in classOptions" :key="item.classId" :label="item.className" :value="item.classId" />
          </el-select>
        </el-form-item>
        <el-form-item label="学生ID" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学生ID" />
        </el-form-item>
        <el-form-item label="教师ID" prop="teacherId">
          <el-input v-model="form.teacherId" placeholder="请输入教师ID" />
        </el-form-item>
        <el-form-item label="惩罚等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择惩罚等级" style="width: 100%">
            <el-option label="警告" value="警告" />
            <el-option label="严重警告" value="严重警告" />
            <el-option label="记过" value="记过" />
            <el-option label="留校察看" value="留校察看" />
            <el-option label="开除学籍" value="开除学籍" />
          </el-select>
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker v-model="form.recordTime" type="date" placeholder="选择日期" style="width: 100%"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="审核状态" prop="reviewStatus">
          <el-input v-model="form.reviewStatus" disabled />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../api/request'
import axios from 'axios'

const punishmentList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加惩罚记录')
const formRef = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 学期和班级选项
const semesterOptions = ref(['2023-2024-1', '2023-2024-2'])
const classOptions = ref([
  { classId: '1', className: '23级区块链' },
  { classId: '2', className: '23级区块链二班' },
  { classId: '3', className: '23级软件开发班' },
  { classId: '4', className: '23级区块链3班' }
])

const form = reactive({
  recordId: null,
  studentId: '',
  teacherId: '',
  penaltyItemId: '',
  level: '警告',
  recordTime: new Date().toISOString().split('T')[0],
  reviewStatus: '未审核',
  description: '',
  semester: null,
  classId: null
})

const rules = {
  studentId: [{ required: true, message: '请选择学生', trigger: 'change' }],
  teacherId: [{ required: true, message: '请选择教师', trigger: 'change' }],
  penaltyItemId: [{ required: true, message: '请选择处罚项目', trigger: 'change' }],
  level: [{ required: true, message: '请选择惩罚等级', trigger: 'change' }],
  recordTime: [{ required: true, message: '请选择记录时间', trigger: 'change' }],
  reviewStatus: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }]
}

// 计算属性：过滤后的惩罚记录
const filteredPunishmentList = computed(() => {
  let result = punishmentList.value
  if (form.semester && form.semester !== '') {
    result = result.filter(item => item.semester === form.semester)
  }
  if (form.classId && form.classId !== '') {
    result = result.filter(item => item.classId.toString() === form.classId.toString())
  }
  return result
})

// 计算属性：分页后的惩罚记录
const paginatedPunishmentList = computed(() => {
  const data = filteredPunishmentList.value || []; // 确保数据不为 undefined 或 null
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return data.slice(start, end)
})

// 添加学生和教师数据
const studentList = ref([]);
const teacherList = ref([]);

// 获取惩罚记录
const fetchPunishments = async () => {
  try {
    const response = await axios.get('/punishment');
    punishmentList.value = response.data.data || []; // 确保数据不为 undefined 或 null
  } catch (error) {
    console.error('获取惩罚记录失败:', error);
    ElMessage.error('获取惩罚记录失败');
  }
};

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 监听筛选条件变化
watch([() => form.semester, () => form.classId], () => {
  currentPage.value = 1
  total.value = filteredPunishmentList.value.length
})

// 审核惩罚记录
const handleReview = async (row) => {
  try {
    await ElMessageBox.confirm('确定要审核通过该惩罚记录吗？', '审核确认', {
      confirmButtonText: '通过',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await api.punishment.review(row.recordId);
    if (res.code === 1) {
      ElMessage.success('审核成功');
      const index = punishmentList.value.findIndex(item => item.recordId === row.recordId);
      if (index !== -1) {
        punishmentList.value.splice(index, 1, { 
          ...punishmentList.value[index],
          reviewStatus: '已审核'
        });
      }
    } else {
      ElMessage.error(res.msg || '审核失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核惩罚记录出错:', error);
      ElMessage.error('审核失败: ' + (error.message || '未知错误'));
    }
  }
};

// 删除惩罚记录
const handleDelete = async (id) => {
  try {
    // 测试直接访问后端端口
    await axios.delete(`http://localhost:8080/punishment/${id}`);
    ElMessage.success('删除成功');
    fetchPunishments();
  } catch (error) {
    console.error('删除惩罚记录出错:', error);
    ElMessage.error('删除惩罚记录出错');
  }
};

// 添加惩罚记录
const handleAdd = () => {
  dialogTitle.value = '添加惩罚记录'
  form.recordId = null
  form.studentId = ''
  form.teacherId = ''
  form.penaltyItemId = ''
  form.level = '警告'
  form.recordTime = new Date().toISOString().split('T')[0]
  form.reviewStatus = '未审核'
  form.description = ''
  dialogVisible.value = true
}

// 编辑惩罚记录
const handleEdit = (row) => {
  dialogTitle.value = '编辑惩罚记录'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    if (form.recordId) {
      // 更新记录
      const res = await api.punishment.update(form)
      if (res.code === 1) {
        ElMessage.success('更新成功')
        fetchPunishments()
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    } else {
      // 添加记录
      const res = await api.punishment.add(form)
      if (res.code === 1) {
        ElMessage.success('添加成功')
        fetchPunishments()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    }
    dialogVisible.value = false
  } catch (error) {
    console.error('提交表单出错:', error)
    ElMessage.error('提交失败')
  }
}

// 获取学生和教师数据
onMounted(async () => {
    loading.value = true;
    try {
        // 并行加载学生、教师和惩罚数据
        const [studentsRes, teachersRes, punishmentsRes] = await Promise.all([
            api.student.getAll(),
            api.teacher.getAll(),
            api.punishment.getAll()
        ]);

        studentList.value = studentsRes.data || [];
        teacherList.value = teachersRes.data || [];

        if (punishmentsRes.code === 1) {
            punishmentList.value = punishmentsRes.data || [];
            total.value = punishmentList.value.length;
        } else {
            ElMessage.error(punishmentsRes.msg || '获取惩罚记录失败');
        }
    } catch (error) {
        console.error('加载数据出错:', error);
        ElMessage.error('加载数据失败');
    } finally {
        loading.value = false;
    }
});

// 添加学生名称映射方法
const getStudentName = (studentId) => {
    if (!studentId) {
        console.warn('学生ID为空:', studentId);
        return '未知学生';
    }
    const student = studentList.value.find(item => item.studentId === Number(studentId));
    if (!student) {
        console.warn('未找到匹配的学生:', studentId, '学生列表:', studentList.value);
    }
    return student ? student.name : '未知学生';
};

// 添加教师名称映射方法
const getTeacherName = (teacherId) => {
    if (!teacherId) {
        console.warn('教师ID为空:', teacherId);
        return '未知教师';
    }
    const teacher = teacherList.value.find(item => item.teacherId === Number(teacherId));
    if (!teacher) {
        console.warn('未找到匹配的教师:', teacherId, '教师列表:', teacherList.value);
    }
    return teacher ? teacher.name : '未知教师';
};

// 初始化加载数据
onMounted(() => {
  fetchPunishments()
})
</script>

<style scoped>
.container {
    padding: 20px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}
</style>